package kuaidi;

import until.DBUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.sql.*;
import java.util.Random;

public class ImportPanel extends JPanel {
    private JTextField phoneField;
    private JComboBox<String> sizeBox;

    public ImportPanel() {
        setLayout(new GridBagLayout());
        setBackground(Color.WHITE);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(15, 15, 15, 15);
        gbc.anchor = GridBagConstraints.WEST;

        JLabel phoneLabel = new JLabel("客户手机号：");
        phoneLabel.setFont(new Font("微软雅黑", Font.PLAIN, 20));
        gbc.gridx = 0;
        gbc.gridy = 0;
        add(phoneLabel, gbc);

        phoneField = new JTextField(15);
        phoneField.setFont(new Font("微软雅黑", Font.PLAIN, 20));
        gbc.gridx = 1;
        add(phoneField, gbc);

        JLabel sizeLabel = new JLabel("柜子尺寸：");
        sizeLabel.setFont(new Font("微软雅黑", Font.PLAIN, 20));
        gbc.gridx = 0;
        gbc.gridy = 1;
        add(sizeLabel, gbc);

        String[] sizes = {"小柜", "中柜", "大柜"};
        sizeBox = new JComboBox<>(sizes);
        sizeBox.setFont(new Font("微软雅黑", Font.PLAIN, 20));
        gbc.gridx = 1;
        add(sizeBox, gbc);

        JButton importBtn = new JButton("导入包裹");
        importBtn.setFont(new Font("微软雅黑", Font.BOLD, 20));
        importBtn.setBackground(new Color(60, 179, 113));
        importBtn.setForeground(Color.WHITE);
        importBtn.setFocusPainted(false);
        importBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        add(importBtn, gbc);

        importBtn.addActionListener(this::handleImport);
    }

    private void handleImport(ActionEvent e) {
        String phone = phoneField.getText().trim();
        String size = (String) sizeBox.getSelectedItem();

        if (phone.isEmpty() || !phone.matches("\\d{11}")) {
            JOptionPane.showMessageDialog(this, "请输入合法的11位手机号！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            // 查找空闲柜子
            String lockerQuery = "SELECT id FROM lockers WHERE status = '空闲' AND size = ? LIMIT 1";
            PreparedStatement lockerStmt = conn.prepareStatement(lockerQuery);
            lockerStmt.setString(1, size);
            ResultSet rs = lockerStmt.executeQuery();

            if (rs.next()) {
                int lockerId = rs.getInt("id");
                String code = generatePickupCode();

                // 插入 parcels，使用参数传递 "未取"
                String insertParcel = """
                    INSERT INTO parcels (phone, size, code, locker_id, status, create_time)
                    VALUES (?, ?, ?, ?, ?, NOW())
                """;
                PreparedStatement insertStmt = conn.prepareStatement(insertParcel);
                insertStmt.setString(1, phone);
                insertStmt.setString(2, size);
                insertStmt.setString(3, code);
                insertStmt.setInt(4, lockerId);
                insertStmt.setString(5, "未取");
                insertStmt.executeUpdate();

                // 更新 lockers 状态
                String updateLocker = "UPDATE lockers SET status = '已占用' WHERE id = ?";
                PreparedStatement updateStmt = conn.prepareStatement(updateLocker);
                updateStmt.setInt(1, lockerId);
                updateStmt.executeUpdate();

                JOptionPane.showMessageDialog(this,
                        "导入成功！\n取件码：" + code + "\n柜子编号：" + lockerId,
                        "成功", JOptionPane.INFORMATION_MESSAGE);

                phoneField.setText("");

            } else {
                JOptionPane.showMessageDialog(this,
                        "没有可用的 " + size + "！", "失败", JOptionPane.WARNING_MESSAGE);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this,
                    "导入失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private String generatePickupCode() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb = new StringBuilder();
        Random rand = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(chars.charAt(rand.nextInt(chars.length())));
        }
        return sb.toString();
    }
}
